package org.example.shoppingsystem.dao;
import org.example.shoppingsystem.model.User;

import java.sql.*;
public class UserDaoImpl implements UserDao {
    private static final String URL = "jdbc:mysql://localhost:3306/shopping_system";
    private static final String USER = "root";
    private static final String PASSWORD = "123456";

    @Override
    public User findUserByAccount(String account) throws SQLException {
        Connection conn = null;
        PreparedStatement stmt = null;
        ResultSet rs = null;
        User user = null;

        try {
            // 加载数据库驱动
            Class.forName("com.mysql.cj.jdbc.Driver");
            // 建立数据库连接
            conn = DriverManager.getConnection(URL, USER, PASSWORD);
            // 准备预编译语句
            String sql = "SELECT * FROM users WHERE account = ? AND is_deleted = 0";
            stmt = conn.prepareStatement(sql);
            stmt.setString(1, account);
            // 执行查询
            rs = stmt.executeQuery();

            if (rs.next()) {
                // 创建用户对象并设置属性
                user = new User();
                user.setId(rs.getInt("id"));
                user.setUsername(rs.getString("username"));
                user.setPassword(rs.getString("password"));
                user.setAccount(rs.getString("account"));
                user.setCreateTime(rs.getTimestamp("create_time"));
                user.setUpdateTime(rs.getTimestamp("update_time"));
                user.setIsDeleted(rs.getInt("is_deleted"));
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            // 关闭资源
            try {
                if (rs != null) rs.close();
                if (stmt != null) stmt.close();
                if (conn != null) conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return user;
    }
    @Override
    public int registerUser(User user) throws SQLException {
        Connection conn = null;
        PreparedStatement stmt = null;
        int rows = 0;

        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            conn = DriverManager.getConnection(URL, USER, PASSWORD);
            String sql = "INSERT INTO users (username, password, account) VALUES (?, ?, ?)";
            stmt = conn.prepareStatement(sql);
            stmt.setString(1, user.getUsername());
            stmt.setString(2, user.getPassword());
            stmt.setString(3, user.getAccount());
            rows = stmt.executeUpdate();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            try {
                if (stmt != null) stmt.close();
                if (conn != null) conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return rows;
    }
}